// debug utilities
// $Id: dbg_util.cpp 718 2012-06-04 17:02:38Z Oleg.Bulychov@gmail.com $

#include "stdafx.h"

#if defined(_WIN32)

#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <conio.h>

#endif

#if defined(_MSC_VER) && (_MSC_VER >= 1400)

#ifdef _DEBUG 
//_____________________________________________________________________________
#define SET_CRT_DEBUG_FIELD(a)   _CrtSetDbgFlag((a) | _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG))
#define CLEAR_CRT_DEBUG_FIELD(a) _CrtSetDbgFlag(~(a) & _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG))
//_____________________________________________________________________________
struct MemDebug
{
    MemDebug()
    {
        _CrtSetReportMode(_CRT_WARN,   _CRTDBG_MODE_DEBUG);
        _CrtSetReportMode(_CRT_ERROR,  _CRTDBG_MODE_DEBUG);
        //_CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_DEBUG);

        //SET_CRT_DEBUG_FIELD(_CRTDBG_ALLOC_MEM_DF);
        //SET_CRT_DEBUG_FIELD(_CRTDBG_DELAY_FREE_MEM_DF);
        SET_CRT_DEBUG_FIELD(_CRTDBG_CHECK_EVERY_1024_DF);
        SET_CRT_DEBUG_FIELD(_CRTDBG_LEAK_CHECK_DF);
    }
} mdbg;
//_____________________________________________________________________________
#endif //_DEBUG

#endif //_MSC_VER


void My_Assert(char const* szExpression, char const* szFile,
               unsigned nLine) NO_THROW_()
{
    printf("FATAL ERROR:\n");
    printf("%s(%d)\n", szFile, nLine);
    printf(szExpression);
    printf("\n");
#if defined(_WIN32)
    OutputDebugStringA("FATAL ERROR:\r\n");
    static char buff[256];
    sprintf(buff, "%s(%d)\n", szFile, nLine);
    OutputDebugStringA(buff);
    OutputDebugStringA(szExpression);
    OutputDebugStringA("\r\n");
#endif
}

void My_Exit(bool bForce)
{
    if (!bForce)
    {
#if defined(_WIN32)
    if (::IsDebuggerPresent())
        return;
#endif
    }
    exit(EXIT_FAILURE);
}

void If_Debug_Press_Enter()
{
#if defined(_WIN32)
    if (!::IsDebuggerPresent())
        return;
    HANDLE h = ::GetStdHandle(STD_OUTPUT_HANDLE);
    if (!h || INVALID_HANDLE_VALUE == h)
        return;
    if (::GetFileType(h) != FILE_TYPE_CHAR)//:stdout is not redirected
        return;
    printf("press <enter>");
    _getch();
#endif
}

//EOF!
